using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace HDCustomAction
{
    public partial class SqlBrowserForm : Form
    {
        private string _sqlServer = string.Empty;
        public string SQLServer { get { return _sqlServer; } }

        private bool threadFinished;
        private Thread _thread;
        private DataTable dt;

        public SqlBrowserForm()
        {
            InitializeComponent();
        }

        private void SqlBrowserForm_Shown(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            _thread = new Thread(new ThreadStart(ThreadProc));
            threadFinished = false;
            _thread.Start();

            //wait for the thread
            while (!threadFinished)
            {
                Application.DoEvents();
                Thread.Sleep(50);
            }

            if (dt.Rows.Count > 0)
            {
                string srvName, instanceName;
                lstServers.Items.Clear();
                foreach (DataRow dr in dt.Rows)
                {
                    srvName = dr["ServerName"].ToString();
                    instanceName = dr["InstanceName"].ToString();
                    srvName = srvName + (instanceName == "" ? "" : "\\" + instanceName);
                    lstServers.Items.Add(srvName);
                }
            }
            else
            {
                lstServers.Items.Add("No servers found in your local network...");
                lstServers.Enabled = false;
            }
            lblWait.Visible = false;
            btnCancel.Enabled = true;
            this.Cursor = Cursors.Default;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            _sqlServer = string.Empty;
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (lstServers.SelectedItem != null)
            {
                _sqlServer = lstServers.SelectedItem.ToString();
            }
            this.Close();
        }

        private void lstServers_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnOK.Enabled = lstServers.SelectedItem != null;
        }

        private void ThreadProc()
        {
            System.Data.Sql.SqlDataSourceEnumerator sqlEnum = System.Data.Sql.SqlDataSourceEnumerator.Instance;
            dt = sqlEnum.GetDataSources();
            threadFinished = true;
        }

        private void SqlBrowserForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = !btnCancel.Enabled;
        }
    }
}